import React, { Component } from 'react'
import {connect} from 'react-redux'
import {CProduct} from '../../../types/product'
import CarProduct from '../../../component/carProduct'
import './car.scss'

interface IProps{
    carList:CProduct[],
    delPro:(id:number) => void,
    checkAll:boolean,
    checkAllFun:(checked:boolean) => void
}

interface IState{
    isShow:boolean,
    id:number
}

class Car extends Component <IProps,IState>{
    state = {
        isShow:false,
        id:-1
    }
    render() {
        let {carList,checkAll} = this.props;
        let {isShow} = this.state;
        let totalMoney = 0;
        
        carList.forEach((item:CProduct) => {
            if(item.checked){
                totalMoney += item.num *item.price
            }
        })
        return (
            <div>
                <div>
                    <div>
                        {carList.length && carList.map((item:CProduct) => <CarProduct open={this.open} key={item.id} {...item}></CarProduct>)}
                    </div>
                    <div>
                        全选: <input type="checkbox" checked={checkAll} onChange={() => {
                            this.props.checkAllFun(!checkAll)
                        }}/>
                        总价格：{totalMoney}
                    </div>
                </div>
                {/* //弹窗 */}
                <div className="dialog" style={{display:isShow?'block':'none'}}>
                    <h4>是否确定删除?</h4>
                    <div>
                        <button onClick={this.close}>取消</button>
                        <button onClick={this.del}>确定</button>
                    </div>
                </div>
            </div>
        )
    }

    //打开弹窗
    open = (id:number) => {
        console.log("34567890")
        this.setState({
            isShow:true,
            id  //删除的商品id
        })
    }

    //关闭弹窗
    close = () => {
        this.setState({
            isShow:false
        })
    }

    //确定删除
    del = () => {
        let {id} = this.state;
        this.props.delPro(id);
        this.close();//关掉弹窗
    }
}

let stateMapToProps = (state:any) => {
    return {
        carList:state.car.carList,
        checkAll:state.car.checkAll
    }
}

let dispatchMapToProps = (dispatch:any) => {
    return {
        delPro(id:number){
            dispatch({type:'DEL_PRO',id})
        },
        checkAllFun(checked:boolean){
            dispatch({type:'CHANGE_CHEAKALL',checked})
        }
    }
}

export default connect(stateMapToProps,dispatchMapToProps)(Car)
